package com.mainworks.commons.utils;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.mainworks.commons.entity.GoogleKaptcha;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Author: HuangMinJie
 * @CreateDate: 2021/10/31 12:56
 * @Description:
 * @Version: 1.0.0.0
 * @ModifiedBy:
 * @ModifiedDate:
 * @ModifiedDescription:
 */
public class IPInetAddress {
    /**
     * 获取主机IP地址
     *@Author: HuangMinJie
     *@CreateDate:  2021/10/31 13:10
     *@Description:
     */
    public static String getHostAddress(){
        String ip = "";
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            ip = "UnknownHostException";
        }
        return ip;
    }
    /**
     * 获取请求的真实ip
     *@Author: HuangMinJie
     *@param  request
     *@CreateDate:  2021/10/31 13:10
     *@Description:
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for")==null?null:request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP")==null?null:request.getHeader("x-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP")==null?null:request.getHeader("x-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP")==null?null:request.getHeader("x-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR")==null?null:request.getHeader("x-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip != null && ip.length() > 0 ) {
            ip = ip.replaceAll("/","");//.split(":")[0];//request.getRemoteAddress().toString();
            ip = ip.replaceAll("\\[","");
            ip = ip.replaceAll("]","");
            ip = ip.split(":")[0];
            if (ip.indexOf("localhost")>-1||ip.indexOf("127.0.0.1")>-1||ip.indexOf("::1")>-1||ip.indexOf("0:0:0:0:0:0:0:1")>-1){
                String ips =getHostAddress();
                if (!"UnknownHostException".equals(ips)){
                    ip = ips;
                }
            }
        }
        return ip;
    }

    public static String createCaptcha() {
        DefaultKaptcha defaultKaptcha= GoogleKaptcha.defaultKaptcha();
        return defaultKaptcha.createText();
    }
}
